// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package proxy

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"sync/atomic"

	"github.com/fatih/color"
	logprinter "github.com/kumose/kmopt/pkg/logger/printer"
	"github.com/kumose/kmopt/pkg/tui"
	"github.com/kumose/kmopt/pkg/utils"
)

var (
	httpProxy *http.Server
	tcpProxy  atomic.Value
)

// MaybeStartProxy maybe starts an inner http/tcp proxies
func MaybeStartProxy(
	host string,
	port int,
	user string,
	usePass bool,
	identity string,
	logger *logprinter.Logger,
) error {
	if len(host) == 0 {
		return nil
	}

	sshProps, err := tui.ReadIdentityFileOrPassword(identity, usePass)
	if err != nil {
		return err
	}

	httpPort := utils.MustGetFreePort("127.0.0.1", 12345, 0)
	addr := fmt.Sprintf("127.0.0.1:%d", httpPort)

	// TODO: Using environment variables to share data may not be a good idea
	os.Setenv("KMOPT_INNER_HTTP_PROXY", "http://"+addr)
	httpProxy = &http.Server{
		Addr: addr,
		Handler: NewHTTPProxy(
			host, port, user,
			sshProps.Password,
			sshProps.IdentityFile,
			sshProps.IdentityFilePassphrase,
			logger,
		),
	}

	logger.Infof("%s", color.HiGreenString("Start HTTP inner proxy %s", httpProxy.Addr))
	go func() {
		if err := httpProxy.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			logger.Errorf("Failed to listen HTTP proxy: %v", err)
		}
	}()

	p := NewTCPProxy(
		host, port, user,
		sshProps.Password,
		sshProps.IdentityFile,
		sshProps.IdentityFilePassphrase,
		logger,
	)
	tcpProxy.Store(p)

	logger.Infof("%s", color.HiGreenString("Start TCP inner proxy %s", p.endpoint))

	return nil
}

// MaybeStopProxy stops the http/tcp proxies if it has been started before
func MaybeStopProxy() {
	if httpProxy != nil {
		_ = httpProxy.Shutdown(context.Background())
		os.Unsetenv("KMOPT_INNER_HTTP_PROXY")
	}
	if p := tcpProxy.Load(); p != nil {
		_ = p.(*TCPProxy).Stop()
	}
}

// GetTCPProxy returns the tcp proxy
func GetTCPProxy() *TCPProxy {
	p := tcpProxy.Load()
	if p != nil {
		return p.(*TCPProxy)
	}
	return nil
}
